package cc.rengu.igas.mcps.core.service.trans.scanpay;

import cc.rengu.igas.channel.alipay.facade.request.AliGetUserIdRequest;
import cc.rengu.igas.channel.alipay.facade.response.AliGetUserIdResponse;
import cc.rengu.igas.channel.wechat.facade.request.WechatGetOpenIdRequest;
import cc.rengu.igas.channel.wechat.facade.response.WechatGetOpenIdResponse;
import cc.rengu.igas.channel.wechat.facade.result.Result;
import cc.rengu.igas.mcps.common.constant.McpsParamConstant;
import cc.rengu.igas.mcps.common.enums.RespCodeEnum;
import cc.rengu.igas.mcps.core.service.base.QrManageService;
import cc.rengu.igas.mcps.facade.base.Header;
import cc.rengu.igas.mcps.facade.request.GetUserAuthInfoRequest;
import cc.rengu.igas.mcps.facade.response.GetUserAuthInfoResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alibaba.fastjson.JSON;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 获取用户授权信息 openId.
 */
public class McpsGetUserAuthInfoService extends QrManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        GetUserAuthInfoRequest request = new GetUserAuthInfoRequest();
        // 读取存在xml树里的实体类
        ConvertUtil.convertOutput(request);
        xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.FRONT_SEQ_NUM, request.getHeader().getTraceNo());
        return request;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        GetUserAuthInfoRequest getUserAuthInfoRequest = (GetUserAuthInfoRequest) request;
        Header header = getUserAuthInfoRequest.getHeader();
        String authChannel = getUserAuthInfoRequest.getAuthChannel();
        GetUserAuthInfoResponse response = new GetUserAuthInfoResponse();

        //区分支付宝与微信
        if ("WECHAT".equals(authChannel.toUpperCase())) {

            List<ChannelCallCfg> txnNumList = txnInfo.getChannelCallCfgList().stream().filter(item -> ChannelEnum.WXZF.getChannelType().equals(item.getCallChannelId())).collect(Collectors.toList());
            if (txnNumList.isEmpty()) {
                rglog.error("未配置微信用户获取OPENID的通道交易映射关系");
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }

            cc.rengu.igas.channel.wechat.facade.base.Header wechatHeader = new cc.rengu.igas.channel.wechat.facade.base.Header();
            wechatHeader.setVersion("1.0.0");
            wechatHeader.setTransDate(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_DATE));
            wechatHeader.setTransTime(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_TIME));
            //getopenid
            wechatHeader.setTxnNum(txnNumList.get(0).getCallChannelTxn());
            wechatHeader.setBizType(AppParamConstant.DEFAULT_BIZ_TYPE);
            wechatHeader.setInstId(getUserAuthInfoRequest.getHeader().getInstId());
            wechatHeader.setSrcSysId(AppParamConstant.IGAS);
            wechatHeader.setChanlId(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SRC_SYS_ID));
            wechatHeader.setTraceNo(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM) + txnNumList.get(0).getCallIndex());

            WechatGetOpenIdRequest wechatGetOpenIdRequest = new WechatGetOpenIdRequest();
            wechatGetOpenIdRequest.setHeader(wechatHeader);
            wechatGetOpenIdRequest.setChannelId(getUserAuthInfoRequest.getAuthChannel());
            wechatGetOpenIdRequest.setAuthCode(getUserAuthInfoRequest.getCode());
            wechatGetOpenIdRequest.setChannelId(ChannelEnum.WXZF.getChannelType());
            rglog.debug("微信获取用户openId-dubbo请求:<{}>", JSON.toJSONString(wechatGetOpenIdRequest));
            DubboService dubboService = new DubboServiceImpl();
            Result<WechatGetOpenIdResponse> wechatResponse = (Result<WechatGetOpenIdResponse>) dubboService.callDubboService("wechatPubService", "getOpenId", wechatGetOpenIdRequest);
            if (!wechatResponse.isSuccess() || !McpsParamConstant.DUBBO_SUCCESS.equals(wechatResponse.getResult().getRespCode())) {
                rglog.error("调用微信服务失败,errorCode:<{}>,errorMsg:<{}>", wechatResponse.getResult().getRespCode(), wechatResponse.getResult().getRespDesc());
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }

            response.setUserId(wechatResponse.getResult().getOpenId());
        } else if ("ALIPAY".equals(authChannel.toUpperCase())) {

            List<ChannelCallCfg> txnNumList = txnInfo.getChannelCallCfgList().stream().filter(item -> ChannelEnum.ALIP.getChannelType().equals(item.getCallChannelId())).collect(Collectors.toList());
            if (txnNumList.isEmpty()) {
                rglog.error("未配置支付宝用户获取OPENID的通道交易映射关系");
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }

            cc.rengu.igas.channel.alipay.facade.base.Header alipayHeader = new cc.rengu.igas.channel.alipay.facade.base.Header();
            alipayHeader.setVersion("1.0.0");
            alipayHeader.setTransDate(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_DATE));
            alipayHeader.setTransTime(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_TIME));
            //agetuserid
            alipayHeader.setTxnNum(txnNumList.get(0).getCallChannelTxn());
            alipayHeader.setBizType(AppParamConstant.DEFAULT_BIZ_TYPE);
            alipayHeader.setInstId(getUserAuthInfoRequest.getHeader().getInstId());
            alipayHeader.setSrcSysId(AppParamConstant.IGAS);
            alipayHeader.setChanlId(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SRC_SYS_ID));
            alipayHeader.setTraceNo(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM) + txnNumList.get(0).getCallIndex());

            AliGetUserIdRequest aliGetUserIdRequest = new AliGetUserIdRequest();
            aliGetUserIdRequest.setHeader(alipayHeader);
            aliGetUserIdRequest.setChannelId(getUserAuthInfoRequest.getAuthChannel());
            aliGetUserIdRequest.setAuthCode(getUserAuthInfoRequest.getCode());
            aliGetUserIdRequest.setChannelId(ChannelEnum.ALIP.getChannelType());
            aliGetUserIdRequest.setChannelType("");
            rglog.debug("支付宝获取用户openId-dubbo请求:<{}>", JSON.toJSONString(aliGetUserIdRequest));
            DubboService dubboService = new DubboServiceImpl();
            cc.rengu.igas.channel.alipay.facade.result.Result<AliGetUserIdResponse> aliResult = (cc.rengu.igas.channel.alipay.facade.result.Result<AliGetUserIdResponse>) dubboService.callDubboService("alipayPubService", "aliGetUserId", aliGetUserIdRequest);
            if (!aliResult.isSuccess() || !McpsParamConstant.DUBBO_SUCCESS.equals(aliResult.getResult().getRespCode())) {
                rglog.error("调用支付宝服务失败,errorCode:<{}>,errorMsg:<{}>", aliResult.getResult().getRespCode(), aliResult.getResult().getRespDesc());
                throw new BizException(aliResult.getResult().getRespCode(), aliResult.getResult().getRespDesc());
            }
            response.setUserId(aliResult.getResult().getAliUserId());
        } else {
            rglog.error("暂不支持获取该渠道的用户信息,机构号:<{}>, AuthChannel:<{}>", header.getInstId(), getUserAuthInfoRequest.getAuthChannel());
            throw new BizException(RespCodeEnum.REQUEST_ERROR.getRespCode(), RespCodeEnum.REQUEST_ERROR.getRespDesc());
        }

        response.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        response.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        BizResponse<GetUserAuthInfoResponse> bizResponse = new BizResponse<>();
        ConvertUtil.convertOutput(response);
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(response);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        GetUserAuthInfoResponse getUserAuthInfoResponse = (GetUserAuthInfoResponse) bizResponse.getResult();
        ConvertUtil.convertInput(getUserAuthInfoResponse);
    }
}
